package com.cbh.amadeus.client.handler;

import com.cbh.amadeus.client.core.Subscriber;
import com.cbh.amadeus.client.receiver.component.SubscriberComponent;
import com.cbh.amadeus.client.receiver.consumer.MessageConsumerProxy;
import com.cbh.amadeus.common.enums.MessageType;
import com.cbh.amadeus.common.protocol.AmadeusMessageWrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ChenBiHui
 * @date 2025/4/28
 */
@Slf4j
public class ReceiveHandler extends SimpleChannelInboundHandler<AmadeusMessageWrap> {

    private final SubscriberComponent component;

    public ReceiveHandler(SubscriberComponent component) {
        this.component = component;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AmadeusMessageWrap msg) {
        MessageType type = MessageType.find(msg.getType());
        if (type == MessageType.GEN) {
            MessageConsumerProxy consumer = component.getConsumer();
            Channel channel = ctx.channel();
            Subscriber.DEFAULT.execute(() -> consumer.receive(channel, msg.getMessage()));
            return;
        }
        if (type == MessageType.RESEND) {
            MessageConsumerProxy consumer = component.getConsumer();
            Channel channel = ctx.channel();
            Subscriber.DEFAULT.execute(() -> consumer.resend(channel, msg.getMessage()));
            return;
        }
        ctx.fireChannelRead(msg);
    }
}
